package com.lovo.manage_back.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lovo.manage_back.result.Result;
import com.lovo.manage_back.result.ResultCode;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

public class WebUtil {
    public static void writeValueAsString(ServletResponse response, Result result) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().print(mapper.writeValueAsString(result));


    }
    /**
     * 获取请求信息中的token
     * @param request
     * @return
     */
    public static String getToken(ServletRequest request){
        HttpServletRequest httpServletRequest = ((HttpServletRequest)request);
        String token = httpServletRequest.getHeader("Authorization");// 从 http 请求头中取出 token
        if(token == null || !token.startsWith("Bearer ")){
            return null;
        }
        return token.substring(7);

    }
}
